package com.toe.sso.controller;


import com.toe.common.restful.JsonResult;
import com.toe.common.utils.AliYunSmsUtils;
import com.toe.sso.pojo.dto.UserLoginDTO;
import com.toe.sso.pojo.vo.TokenVO;
import com.toe.sso.security.service.user.IUserSSOService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * 实现前台用户登录的请求和登出请求
 */
@RestController
@RequestMapping(value = "/user/sso", produces = "application/json; charset=utf-8")
@Api(tags = "前台管理用户认证")
@Slf4j
public class UserSSOController {
    @Autowired
    private IUserSSOService userSSOService;
    @Value("${jwt.tokenHead}")
    private String jwtTokenHead;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "前台单点登录认证登录(手机号+密码)")
    @PostMapping("/login")
    public JsonResult<TokenVO> doLogin(@RequestBody @Validated UserLoginDTO userLoginDTO){
        String token = userSSOService.doLogin(userLoginDTO);
        TokenVO tokenVO = new TokenVO();
        tokenVO.setTokenHeader(jwtTokenHead);
        tokenVO.setTokenValue(token);
        return JsonResult.ok(tokenVO);
    }

    @ApiOperation(value = "前台单点登录认证登录(手机号+验证码)")
    @PostMapping("/login2")
    public JsonResult<TokenVO> doLogin2(@RequestBody @Validated UserLoginDTO userLoginDTO){
        String token = userSSOService.doLogin2(userLoginDTO);
        TokenVO tokenVO = new TokenVO();
        tokenVO.setTokenHeader(jwtTokenHead);
        tokenVO.setTokenValue(token);
        return JsonResult.ok(tokenVO);
    }

    @ApiOperation(value = "发送验证码")
    @GetMapping("/sendCode")
    public JsonResult<Void> sendCode(String phone){
        String code = AliYunSmsUtils.sendCodeSms(phone);
        String key = "code:item:"+phone;
        //测试阶段,先将保存时间调长一点,后期修改
        redisTemplate.opsForValue().set(key,code,3, TimeUnit.DAYS);
        return JsonResult.ok();
    }

    /**
     * <p>登出logout</p>
     * <p>没有任何实际业务逻辑</p>
     */
//    @ApiOperation(value = "前台单点登录认证登出")
//    @PostMapping("/logout")
//    public JsonResult doLogout(@RequestHeader(name = "Authorization") String token){
//        userSSOService.doLogout(token);
//        return JsonResult.ok();
//    }
}
